﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;

namespace Infrastructure
{
    public class ZipProcess
    {
        private static bool IsWork = true;

        private static string root;
        private static string firstpath;
        private static ZipOutputStream zips;
        private static byte[] buffer;
        //public static FILE_BACKUP_INFO FBM_Entity;
        private static Thread threadObj;
        //不备份的文件或文件夹，多个用";"分隔
        public static string STR_NOTBACKUP = "";

        /// <summary>
        /// 压缩文件夹
        /// </summary>
        /// <param name="dirPath">压缩文件夹的路径</param>
        /// <param name="fileName">生成的zip文件路径</param>
        /// <param name="level">压缩级别0-9 0是存储级别 9是最大压缩</param>
        /// <param name="bufferSize">读取文件的缓冲区大小</param>
        /// <param name="ex"></param>
        /// <returns></returns>
        public static bool CreateZip(string dirPath, string fileName, int level, int bufferSize, out Exception ex)
        {
            try
            {
                buffer = new byte[bufferSize];
                zips = new ZipOutputStream(File.Create(fileName));

                zips.SetLevel(level);
                root = dirPath;
                firstpath = dirPath;

                //CreateZipFiles();
                startThread(dirPath);

                ex = null;
                return true;
            }
            catch (Exception e)
            {
                ex = e;
                return false;
            }
        }

        /// <summary>
        /// 压缩文件夹
        /// </summary>
        /// <param name="obj"></param>
        private static void CreateZipFiles(object obj)
        {
            //while (IsWork)
            //{
            try
            {
                //root = root.TrimEnd('//') + "//";
                string[] fileNames = Directory.GetFiles(obj.ToString());
                string[] dirNames = Directory.GetDirectories(obj.ToString());
                string relativePath = obj.ToString().Replace(root, "");
                if (relativePath != "")
                {
                    relativePath = relativePath.Replace("//", "/") + "/";
                }
                //将不备份的文件从数组中删除
                string[] NotBackup = STR_NOTBACKUP.Split(';');
                for (int i = 0; i < NotBackup.Count(); i++)
                {
                    string strCheckFilePath = Directory.GetDirectories(obj.ToString()) + "\\" + NotBackup[i];
                    fileNames = DeleteString(fileNames, strCheckFilePath);
                }
                int sourceBytes;
                //文件备份
                foreach (string file in fileNames)
                {
                    if (IsWork)
                    {
                        ZipEntry entry = new ZipEntry(relativePath + Path.GetFileName(file));
                        entry.DateTime = DateTime.Now;
                        zips.PutNextEntry(entry);
                        sourceBytes = 0;
                        using (FileStream fs = File.OpenRead(file))
                        {
                            do
                            {
                                if (IsWork)
                                {
                                    sourceBytes = fs.Read(buffer, 0, buffer.Length);
                                    zips.Write(buffer, 0, sourceBytes);
                                }
                                else
                                {
                                    break;
                                }
                            }
                            while (sourceBytes > 0);
                        }
                    }
                    else
                    {
                        break;
                    }
                }

                //将不备份的文件夹从数组中删除
                for (int i = 0; i < NotBackup.Count(); i++)
                {
                    string strCheckFilePath = Directory.GetDirectories(obj.ToString()) + "\\" + NotBackup[i];
                    dirNames = DeleteString(dirNames, strCheckFilePath);
                }
                //文件夹备份
                foreach (string dirName in dirNames)
                {
                    if (IsWork)
                    {
                        string relativeDirPath = dirName.Replace(root, "");
                        ZipEntry entry = new ZipEntry(relativeDirPath.Replace("//", "/") + "/");
                        zips.PutNextEntry(entry);
                        CreateZipFiles(dirName);
                    }
                    else
                    {
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                //return (int)Entity.Enums.Common.DataAccess_Enums.DataAccess_Result.Fail;
            }
            //}
            if (obj.ToString() == firstpath)
            {
                zips.Finish();
                zips.Close();
            }
        }

        /// <summary>
        /// 将元素从数组中删除
        /// </summary>
        /// <param name="list"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        private static string[] DeleteString(string[] list, string key)
        {
            List<string> l = new List<string>();
            foreach (string s in list)
            {
                if (s != key)
                    l.Add(s);
            }
            return l.ToArray();
        }

        private static void startThread(string path)
        {
            if (IsWork)
            {
                threadObj = new System.Threading.Thread(
                    new System.Threading.ParameterizedThreadStart(CreateZipFiles));

                threadObj.IsBackground = true;
                threadObj.Start(path);
                //IsWork = true;
            }
        }

        /// <summary>
        /// 停止备份
        /// </summary>
        public static void stopThread()
        {
            IsWork = false;
            threadObj.Interrupt();
            threadObj.Abort();
        }

        public static void CreateZipFile(string filesPath, string zipFilePath)
        {
            if (!Directory.Exists(filesPath))
            {
                throw new Exception(string.Format("未找到压缩文件路径 '{0}'", filesPath));
            }

            try
            {
                string[] filenames = Directory.GetFiles(filesPath);
                using (ZipOutputStream s = new ZipOutputStream(File.Create(zipFilePath)))
                {

                    s.SetLevel(9); // 压缩级别 0-9
                    //s.Password = "123"; //Zip压缩文件密码
                    byte[] buffer = new byte[4096]; //缓冲区大小
                    foreach (string file in filenames)
                    {
                        ZipEntry entry = new ZipEntry(Path.GetFileName(file));
                        entry.DateTime = DateTime.Now;
                        s.PutNextEntry(entry);
                        using (FileStream fs = File.OpenRead(file))
                        {
                            int sourceBytes;
                            do
                            {
                                sourceBytes = fs.Read(buffer, 0, buffer.Length);
                                s.Write(buffer, 0, sourceBytes);
                            } while (sourceBytes > 0);
                        }
                    }
                    s.Finish();
                    s.Close();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("压缩处理过程失败 {0}", ex));
            }
        }

        public static void UnZipFile(string zipFilePath)
        {
            if (!File.Exists(zipFilePath))
            {
                throw new Exception(string.Format("未找到压缩文件路径 '{0}'", zipFilePath));
            }

            using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath)))
            {

                ZipEntry theEntry;
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    //Console.WriteLine(theEntry.Name);

                    string directoryName = Path.GetDirectoryName(theEntry.Name);
                    string fileName = Path.GetFileName(theEntry.Name);

                    // create directory
                    if (directoryName.Length > 0)
                    {
                        Directory.CreateDirectory(directoryName);
                    }

                    if (fileName != String.Empty)
                    {
                        using (FileStream streamWriter = File.Create(theEntry.Name))
                        {

                            int size = 2048;
                            byte[] data = new byte[2048];
                            while (true)
                            {
                                size = s.Read(data, 0, data.Length);
                                if (size > 0)
                                {
                                    streamWriter.Write(data, 0, size);
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
